import { getToken, removeToken, setToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes } from '@/router'
const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes
}
const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    setToken(token)
  },
  REMOVE_TOKEN(state) {
    state.token = ''
    removeToken()
  },
  GET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
  },
  SET_ROUTER(state, newRouter) {
    state.routes = [...constantRoutes, ...newRouter]
  }
}
const actions = {
  async login(context, data) {
    const token = await login(data)
    context.commit('SET_TOKEN', token)
  },
  async getUserInfo(context) {
    const data = await getUserInfo()
    context.commit('GET_USER_INFO', data)
    return data
  },
  logout(context) {
    context.commit('REMOVE_TOKEN')
    context.commit('GET_USER_INFO', {})
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
